package com.demo.datastructure.queue;

/**
 * @author ljr
 * @version 1.0
 * @description: 实现循环队列
 * @date 2021/10/5 21:56
 */
public class MyCircularQueue<E> implements MyQueue<E>{

    //队列大小
    private final int capacity;

    //头部下标
    private int head = 0;

    //尾部下标
    private int tail = 0;

    private Object[] items;

    public MyCircularQueue(int n) {
        if(n == 0) throw new RuntimeException("");
        this.capacity = n;
        items = new Object[capacity];
    }

    @Override
    public boolean enqueue(E value) {
        if((tail + 1) % capacity == head)  return false;
        items[tail] = value;
        tail = (tail+1) % capacity;
        return true;
    }

    @Override
    public E dequeue() {
        if(head == tail) return null;
        E value = (E) items[head];
        items[head] = null;
        head = (head+1) % capacity;
        return value;
    }
}
